package com.youlai.boot.modules.game.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.modules.game.converter.GameInformConverter;
import com.youlai.boot.modules.game.mapper.GameInformLinkMapper;
import com.youlai.boot.modules.game.mapper.GameInformMapper;
import com.youlai.boot.modules.game.mapper.GameInformReadMapper;
import com.youlai.boot.modules.game.model.entity.GameInform;
import com.youlai.boot.modules.game.model.entity.GameInformLink;
import com.youlai.boot.modules.game.model.entity.GameInformRead;
import com.youlai.boot.modules.game.model.form.GameInformForm;
import com.youlai.boot.modules.game.model.query.GameInformQuery;
import com.youlai.boot.modules.game.model.vo.GameInformVO;
import com.youlai.boot.modules.game.service.GameInformService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 游戏通知服务实现类
 *
 * @author 有来技术团队
 */
@Service
@RequiredArgsConstructor
public class GameInformServiceImpl extends ServiceImpl<GameInformMapper, GameInform> implements GameInformService {

    private final GameInformLinkMapper gameInformLinkMapper;
    private final GameInformReadMapper gameInformReadMapper;

    @Override
    public PageResult<GameInformVO> getInformPage(GameInformQuery query) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 构建分页对象
        Page<GameInform> page = new Page<>(query.getPageNum(), query.getPageSize());

        // 查询分页数据
        Page<GameInform> pageResult = baseMapper.getInformPage(page, query, userId);
        List<GameInform> records = pageResult.getRecords();

        // 转换为VO列表
        List<GameInformVO> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            for (GameInform inform : records) {
                GameInformVO vo = GameInformConverter.INSTANCE.entity2vo(inform);
                
                // 查询关联的链接
                if (inform.getId() != null) {
                    List<GameInformLink> links = gameInformLinkMapper.selectList(
                            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GameInformLink>()
                                .eq(GameInformLink::getInformId, inform.getId())
                    );
                    
                    if (CollectionUtil.isNotEmpty(links)) {
                        List<GameInformVO.GameInformLinkVO> linkVOs = 
                            GameInformConverter.INSTANCE.linkEntityList2voList(links);
                        vo.setLinks(linkVOs);
                    }
                }
                
                voList.add(vo);
            }
        }

        return PageResult.success(pageResult.getTotal(), voList);
    }

    @Override
    public GameInformVO getInformDetail(Long id) {
        // 获取通知基本信息
        GameInform inform = this.getById(id);
        if (inform == null) {
            return null;
        }

        // 转换为VO
        GameInformVO vo = GameInformConverter.INSTANCE.entity2vo(inform);
        
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        
        // 查询是否已读
        GameInformRead read = gameInformReadMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GameInformRead>()
                .eq(GameInformRead::getUserId, userId)
                .eq(GameInformRead::getInformId, id)
        );
        vo.setRead(read != null);
        
        // 查询关联的链接
        List<GameInformLink> links = gameInformLinkMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GameInformLink>()
                .eq(GameInformLink::getInformId, id)
        );
        
        if (CollectionUtil.isNotEmpty(links)) {
            List<GameInformVO.GameInformLinkVO> linkVOs = 
                GameInformConverter.INSTANCE.linkEntityList2voList(links);
            vo.setLinks(linkVOs);
        }
        
        return vo;
    }

    @Override
    public boolean markAsRead(Long id) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        
        // 标记通知为已读
        int rows = gameInformReadMapper.markAsRead(id, userId);
        
        return rows > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createInform(GameInformForm formData) {
        // 转换为实体
        GameInform inform = GameInformConverter.INSTANCE.form2entity(formData);
        
        // 保存通知
        this.save(inform);
        
        // 保存关联的链接
        saveInformLinks(inform.getId(), formData.getLinks());
        
        return inform.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateInform(GameInformForm formData) {
        // 获取通知ID
        Long informId = formData.getId();
        if (informId == null) {
            return false;
        }
        
        // 转换为实体
        GameInform inform = GameInformConverter.INSTANCE.form2entity(formData);
        
        // 更新通知
        boolean result = this.updateById(inform);
        
        // 删除原有链接
        gameInformLinkMapper.delete(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GameInformLink>()
                .eq(GameInformLink::getInformId, informId)
        );
        
        // 保存新的链接
        saveInformLinks(informId, formData.getLinks());
        
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteInform(Long id) {
        // 删除通知
        boolean result = this.removeById(id);
        
        if (result) {
            // 删除关联的链接
            gameInformLinkMapper.delete(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GameInformLink>()
                    .eq(GameInformLink::getInformId, id)
            );
            
            // 删除阅读记录
            gameInformReadMapper.delete(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<GameInformRead>()
                    .eq(GameInformRead::getInformId, id)
            );
        }
        
        return result;
    }
    
    /**
     * 保存通知链接
     */
    private void saveInformLinks(Long informId, List<GameInformForm.GameInformLinkForm> links) {
        if (CollectionUtil.isEmpty(links)) {
            return;
        }
        
        List<GameInformLink> linkEntities = links.stream().map(linkForm -> {
            GameInformLink link = GameInformConverter.INSTANCE.linkForm2entity(linkForm);
            link.setInformId(informId);
            return link;
        }).collect(Collectors.toList());
        
        for (GameInformLink link : linkEntities) {
            gameInformLinkMapper.insert(link);
        }
    }
} 